//
//  ExploreViewController.m
//  ShangHaiTuJI
//
//  Created by xiaoxiangtuji on 2017/7/19.
//  Copyright © 2017年 xiaoxiangtuji. All rights reserved.
//

#import "ExploreViewController.h"
#import "ExploreCategroyViewController.h"
#import "YYInfiniteLoopView.h"
#import "NewPagedFlowView.h"
#import "PGIndexBannerSubiew.h"
#import "CataBottomCell.h"
#import "ExploreBlankCell.h"
#import "ExploreContentView.h"
#import "AVAudioAddViewController.h"
#import "ExploreDetailViewController.h"
#import "ExploreAudioDetailViewController.h"
#import "WXApi.h"
#import "AudioPublishViewController.h"
typedef NS_ENUM(NSUInteger,UIButtonResponderType){
    UIButtonIntelligent = 1000,
    UIButtonLearnAbilitys,
    UIButtonListenStory ,
};

@interface ExploreViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,NewPagedFlowViewDelegate,NewPagedFlowViewDataSource,YYInfiniteLoopViewDelegate>{
    NSInteger _showCount;
    NSInteger _currentPage;
}

@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)UICollectionViewFlowLayout *flowLayout;
@property(nonatomic,strong)UIView *headerView;
@property(nonatomic,assign)UIButtonResponderType buttonType;
@property(nonatomic,strong)NSMutableArray *imageArra;
@property(nonatomic,strong)NSMutableArray *LearSkillBottomArray;
@property(nonatomic,strong)NSMutableArray *ListenStoryBottomArray;

@end

@implementation ExploreViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.title = @"秘探";
    self.navigationController.navigationBar.subviews.firstObject.alpha = 0.0f;
    [self createPlaceHolderImageView];
//    [self createHeaderView];
//    [self createCollectionUI];
}
-(void)createPlaceHolderImageView{
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 49)];
    imageView.image = [UIImage imageNamed:@"mitantan.jpg"];
    [self.view addSubview:imageView];
    imageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pageChoose:)];
    [imageView addGestureRecognizer:tap];
}
-(void)pageChoose:(UITapGestureRecognizer *)tap{
    AudioPublishViewController *audioPublishVc = [[AudioPublishViewController alloc] init];
    [self.navigationController pushViewController:audioPublishVc animated:YES];
}
#pragma mark -创建密探的首页头部页面
-(void)createHeaderView{
    self.headerView = [[UIView alloc] init];
    [self.view addSubview:_headerView
     ];
    [_headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.top.equalTo(self.view.mas_top).offset(64);
        make.height.mas_equalTo(scaleTopAndBottom(60));
    }];
    UIButton *intelligentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    intelligentBtn.tag = 1000;
    [intelligentBtn addTarget:self action:@selector(ButtonDialAndResponder:) forControlEvents:UIControlEventTouchUpInside];
    intelligentBtn.backgroundColor = [UIColor purpleColor];
    [_headerView addSubview:intelligentBtn];
    UIButton *learnBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    learnBtn.tag = 1001;
    [learnBtn addTarget:self action:@selector(ButtonDialAndResponder:) forControlEvents:UIControlEventTouchUpInside];
    learnBtn.backgroundColor = [UIColor purpleColor];
    [_headerView addSubview:learnBtn];
    UIButton *listenBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    listenBtn.tag = 1002;
    listenBtn.backgroundColor = [UIColor purpleColor];
    [listenBtn addTarget:self action:@selector(ButtonDialAndResponder:) forControlEvents:UIControlEventTouchUpInside];
    [_headerView addSubview:listenBtn];
    [learnBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_headerView.mas_centerX);
        make.bottom.equalTo(_headerView.mas_bottom);
        make.width.mas_equalTo(intelligentBtn.mas_width);
        make.width.mas_equalTo(listenBtn.mas_width);
        make.top.equalTo(_headerView.mas_top);
    }];
    [intelligentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_headerView.mas_left).offset(scaleLeftAndRight(10));
        make.top.equalTo(_headerView.mas_top);
        make.bottom.equalTo(_headerView.mas_bottom);
        make.right.equalTo(learnBtn.mas_left).offset(scaleLeftAndRight(-80));
    }];
    [listenBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_headerView.mas_right).offset(scaleLeftAndRight(-10));
        make.top.equalTo(_headerView.mas_top);
        make.bottom.equalTo(_headerView.mas_bottom);
        make.left.equalTo(learnBtn.mas_right).offset(scaleLeftAndRight(80));
    }];
}

#pragma mark -图片轮播
- (void)loopViewDelegateAndAddToFatherView:(UIView *)faterView{
    NSArray *array = @[@"1.jpg",@"2.jpg",@"未标题-2.jpg",@"4.jpg",];
    // 类方法
    YYInfiniteLoopView *loopView = [YYInfiniteLoopView
                                    infiniteLoopViewWithImageUrls:array
                                    titles:nil
                                    didSelectedImage:^(NSInteger index) {
                                        NSLog(@"%zd",index);
                                    }];
    // 设置代理
    loopView.delegate = self;
    loopView.timeInterval = 5;
    loopView.currentPageIndicatorColor = [UIColor yellowColor];
    loopView.pagePosition = InfiniteLoopViewPagePositionCenter;
    loopView.animationType = InfiniteLoopViewAnimationTypeCube;
    loopView.frame = CGRectMake(0, 10, WIDTH, scaleTopAndBottom(175));
    [faterView addSubview:loopView];
}
#pragma mark - YYInfiniteLoopViewDelegate
- (void)infiniteLoopView:(YYInfiniteLoopView *)infiniteLoopView
        didSelectedImage:(NSInteger)selectedImageIndex {
    [self didSelectedImageWithIndex:selectedImageIndex];
}

- (void)didSelectedImageWithIndex:(NSInteger)index {
//    AVAudioAddViewController *avVc = [[AVAudioAddViewController alloc] init];
//    [self.navigationController pushViewController:avVc animated:YES];
//    [self getOrderinforwx];
//    [self getOrderinfor];
    [self.navigationController pushViewController:[[ExploreAudioDetailViewController alloc] init] animated:YES];
//    [self getOrderinforwx];
   NSLog(@"点击了%ld",index);
}

/**
 支付宝的支付流程
 */
-(void)getOrderinfor{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = ServerIp@"/payApp/aliPay";
    NSDictionary *parma = @{@"ordersNumber":@"1708211643400009819"};
   [manager POST:url parameters:parma progress:^(NSProgress * _Nonnull uploadProgress) {
   } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
       NSString *orderStr = jsonDic[@"response"][@"cont"][@"orderStr"];
       NSLog(@"请求成功了");
       NSLog(@"这是订单信息%@",orderStr);
       [[AlipaySDK defaultService] payOrder:orderStr fromScheme:MXURLScheme callback:^(NSDictionary *resultDic) {
           NSLog(@"reslut = %@",resultDic);
       }];
   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       NSLog(@"%@",error);
   }];

}
-(void)getOrderinforwx{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //添加一种支持的类型
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json", @"text/xml",nil];
    NSString *url = @"http://192.168.3.13/payApp/wxPay";
    NSDictionary *parma = @{@"ordersNumber":@"1707251317070000035"};
    [manager POST:url parameters:parma progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        PayReq *req = [[PayReq alloc] init];
        req.openID = jsonDic[@"appid"];
        req.partnerId = jsonDic[@"partnerid"];
        req.prepayId = jsonDic[@"prepayid"];
        req.package = jsonDic[@"package"];
        req.nonceStr = jsonDic[@"noncestr"];
        UInt32 timeStamp =[jsonDic[@"timestamp"] intValue];
        req.timeStamp = timeStamp;
        req.sign = jsonDic[@"sign"];
        [WXApi sendReq:req];
        NSLog(@"这是订单信息%@",jsonDic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
}
#pragma mark -创建collectionView
-(void)createCollectionUI{
    self.collectionView.scrollsToTop = YES;
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64 + 70, WIDTH, HEIGHT - 64 - 70) collectionViewLayout:self.flowLayout];
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.collectionView];
    [self.collectionView registerClass:[CataBottomCell class] forCellWithReuseIdentifier:@"CataBottomCell"];
    [self.collectionView registerClass:[ExploreBlankCell class] forCellWithReuseIdentifier:@"ExploreBlankCell"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"exploreHeader"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"Collectionfooter"];
//    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"exploreBottom"];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
}
#pragma mark - collectionView的代理方法
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 4;
    
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 3) {
        return 10;
    }else{
        return 1;
    }
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 3) {
        CataBottomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CataBottomCell" forIndexPath:indexPath];
        return cell;
    }else{
        ExploreBlankCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ExploreBlankCell" forIndexPath:indexPath];
        switch (indexPath.section) {
            case 0:
            {
                [self loopViewDelegateAndAddToFatherView:cell.contentView];
            }
                break;
            case 1:
            {
                [self setupUI:cell.contentView];
            }
                break;
            case 2:
            {
                ExploreContentView *view = [[ExploreContentView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, scaleTopAndBottom(150))];
                [cell.contentView addSubview:view];
            }
                break;
            default:
                break;
        }
        return cell;
    }
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (section == 3) {
        return UIEdgeInsetsMake(5, 8, 5, 8);
    }else{
        return UIEdgeInsetsZero;
    }
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return scaleTopAndBottom(1);
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 3) {
        return CGSizeMake(WIDTH - 20, scaleTopAndBottom(320));
    }else if (indexPath.section == 0){
        return CGSizeMake(WIDTH, scaleTopAndBottom(195));
    }else{
        return CGSizeMake(WIDTH, scaleTopAndBottom(160));
    }
}
#pragma mark - 注册collectionView的头部视图

//collectionview的头部视图的设置
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqual:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"exploreHeader" forIndexPath:indexPath];
            view.backgroundColor = [UIColor whiteColor];
        switch (indexPath.section) {
            case 0:
            {
                view.backgroundColor = [UIColor lightGrayColor];
                return view;
            }
                break;
            case 1:
            {
                [self addHeaderViewContent:view AndChineseTitle:@"最新分类" AndEnglishTitle:@"Special recommend"];
            }
                break;
            case 2:
            {
                [self addHeaderViewContent:view AndChineseTitle:@"特色学习内容" AndEnglishTitle:@"Special recommend"];
            }
                break;
            case 3:
            {
                [self addHeaderViewContent:view AndChineseTitle:@"最新课程" AndEnglishTitle:@"Special recommend"];
            }
                break;
            default:
                break;
        }
        return view;
    }else{
        UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"Collectionfooter" forIndexPath:indexPath];
        view.backgroundColor = [UIColor lightGrayColor];
        return view;
    }
}
//设置头部视图的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return CGSizeMake(0.0f, 0.0f);
    }
    return CGSizeMake(WIDTH, scaleTopAndBottom(50));
}
#pragma mark -头部视图
-(void)addHeaderViewContent:(UIView *)titleView AndChineseTitle:(NSString *)chineTile AndEnglishTitle:(NSString *)engTitle{
    UILabel *label = [[UILabel alloc] init];
    label.text = chineTile;
    label.adjustsFontSizeToFitWidth = YES;
    label.textAlignment = NSTextAlignmentCenter;
    [titleView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(titleView.mas_centerX);
        make.centerY.equalTo(titleView.mas_centerY).offset(scaleTopAndBottom(-5));
        make.width.mas_equalTo(scaleLeftAndRight(80));
        make.height.mas_equalTo(scaleTopAndBottom(20));
    }];
    UIView *view1 = [[UIView alloc] init];
    view1.backgroundColor = [UIColor lightGrayColor];
    [titleView addSubview:view1];
    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleView.mas_left).offset(scaleLeftAndRight(80));
        make.centerY.equalTo(titleView.mas_centerY).offset(scaleTopAndBottom(-5));
        make.height.mas_equalTo(scaleTopAndBottom(1));
        make.right.equalTo(label.mas_left).offset(scaleLeftAndRight(-5));
    }];
    UIView *view2 = [[UIView alloc] init];
    view2.backgroundColor = [UIColor lightGrayColor];
    [titleView addSubview:view2];
    [view2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(titleView.mas_right).offset(scaleLeftAndRight(-80));
        make.centerY.equalTo(titleView.mas_centerY).offset(scaleTopAndBottom(-5));
        make.height.mas_equalTo(scaleTopAndBottom(1));
        make.left.equalTo(label.mas_right).offset(scaleLeftAndRight(5));
    }];
    UILabel *bottomLabel = [[UILabel alloc] init];
    bottomLabel.text = engTitle;
    bottomLabel.adjustsFontSizeToFitWidth = YES;
    bottomLabel.textAlignment = NSTextAlignmentCenter;
    [titleView addSubview:bottomLabel];
    [bottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(label.mas_bottom).offset(0);
        make.width.mas_equalTo(WIDTH);
        make.height.mas_equalTo(scaleTopAndBottom(20));
        make.left.equalTo(titleView.mas_left);
    }];
    
}
//设置尾视图
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeMake(WIDTH, scaleTopAndBottom(5));
}
#pragma mark -创建学本领中间的图片立体手动轮播
- (void)setupUI:(UIView *)view{
    for (UIView *views in view.subviews) {
        [views removeFromSuperview];
    }
    //设置高度 WIDTH * 9 / 16
    NewPagedFlowView *pageFlowView = [[NewPagedFlowView alloc] initWithFrame:CGRectMake(0, scaleTopAndBottom(0), WIDTH, scaleTopAndBottom(150))];
    pageFlowView.delegate = self;
    pageFlowView.dataSource = self;
    pageFlowView.minimumPageAlpha = 0.1;
    pageFlowView.isCarousel = NO;
    pageFlowView.orientation = NewPagedFlowViewOrientationHorizontal;
    pageFlowView.isOpenAutoScroll = YES;
    
    //初始化pageControl
    /****************************
     使用导航控制器(UINavigationController)
     如果控制器中不存在UIScrollView或者继承自UIScrollView的UI控件
     请使用UIScrollView作为NewPagedFlowView的容器View,才会显示正常,如下
     *****************************/
    UIScrollView *bottomScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    [bottomScrollView addSubview:pageFlowView];
    [pageFlowView reloadData];
    [view addSubview:bottomScrollView];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#pragma mark NewPagedFlowView Delegate
- (CGSize)sizeForPageInFlowView:(NewPagedFlowView *)flowView {
    return CGSizeMake(WIDTH -scaleLeftAndRight(60), scaleTopAndBottom(150));
}
- (void)didSelectCell:(UIView *)subView withSubViewIndex:(NSInteger)subIndex {
    
}

#pragma mark NewPagedFlowView Datasource
- (NSInteger)numberOfPagesInFlowView:(NewPagedFlowView *)flowView {
    return 4;
}
- (UIView *)flowView:(NewPagedFlowView *)flowView cellForPageAtIndex:(NSInteger)index{
     NSArray *array = @[@"1.jpg",@"2.jpg",@"未标题-2.jpg",@"4.jpg",];
    PGIndexBannerSubiew *bannerView = (PGIndexBannerSubiew *)[flowView dequeueReusableCell];
    if (!bannerView) {
        bannerView = [[PGIndexBannerSubiew alloc] initWithFrame:CGRectMake(0, 0,WIDTH - scaleLeftAndRight(60), scaleTopAndBottom(150))];
        bannerView.tag = index;
        bannerView.layer.cornerRadius = 4;
        bannerView.layer.masksToBounds = YES;
    }
    bannerView.mainImageView.image = [UIImage imageNamed:array[index]];
//    //在这里下载网络图片
//    OpusListModel *model = self.imageArra[index];
//    [bannerView.mainImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",PictureIp,model.imagepath]] placeholderImage:[UIImage imageNamed:@""]];
//    bannerView.titleLabel.text = model.name;
    return bannerView;
}
- (void)didScrollToPage:(NSInteger)pageNumber inFlowView:(NewPagedFlowView *)flowView {
    NSLog(@"ViewController滚动到了第%ld页",pageNumber);
}

//-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//    ExploreCategroyViewController *explorcateVc = [[ExploreCategroyViewController alloc] init];
//    [self.navigationController pushViewController:explorcateVc animated:YES];
//}

-(void)viewWillAppear:(BOOL)animated{
    CGFloat offset = 0;
    [self.navigationController.navigationBar
     setBackgroundImage:[self imageWithColor:[UIColor colorWithRed:255/255.0 green:201/255.0 blue:31/255.0 alpha:(offset / 64)>0.99?0.99:(offset / 64)]] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar
     setShadowImage:[UIImage new]];
}
-(UIImage*) imageWithColor:(UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
}

@end
